import { LanguageManagerOptions, LanguagePackage, ResourceConfig } from '../types';
import { NetworkManager } from './NetworkManager';
import { ResourceParser } from '../parsers/ResourceParser';
import { logger } from '../../utils/logger';

export class LanguageManager {
  private networkManager?: NetworkManager;
  private resourceParser: ResourceParser;
  private options: LanguageManagerOptions;
  private currentLanguage: string;
  private languagePackages: Map<string, LanguagePackage>;

  constructor(options: LanguageManagerOptions) {
    this.options = options;
    this.currentLanguage = options.defaultLanguage || 'en';
    this.languagePackages = new Map();

    // 初始化网络管理器
    if (options.apiUrl) {
      this.networkManager = new NetworkManager({
        baseUrl: options.apiUrl,
        timeout: options.timeout,
        maxRetries: options.maxRetries
      });
    }

    // 初始化资源解析器
    this.resourceParser = new ResourceParser({
      format: 'auto',
      encoding: 'utf8'
    });
  }

  /**
   * 获取翻译文本
   * @param key 翻译键
   * @param language 可选，覆盖当前语言
   */
  public getText(key: string, language?: string): string {
    const targetLanguage = language || this.currentLanguage;
    const langPackage = this.languagePackages.get(targetLanguage);

    if (langPackage?.data.has(key)) {
      return langPackage.data.get(key)!;
    }

    // 如果找不到翻译，返回键名
    return key;
  }

  /**
   * 设置当前语言
   * @param language 语言代码
   */
  public setLanguage(language: string): void {
    this.currentLanguage = language;
  }

  /**
   * 获取当前语言
   */
  public getCurrentLanguage(): string {
    return this.currentLanguage;
  }

  /**
   * 加载语言包
   * @param language 语言代码
   * @param url 下载地址
   */
  public async loadLanguage(language: string, url: string): Promise<boolean> {
    try {
      logger.info('开始加载语言包', { language, url });

      // 1. 尝试从网络下载
      if (this.networkManager) {
        const langPackage = await this.networkManager.downloadLanguage(language, url);
        if (langPackage) {
          this.languagePackages.set(language, langPackage);
          logger.info('语言包加载成功', { language });
          return true;
        }
      }

      // 2. 如果下载失败，检查是否有本地资源
      const resourceConfig = this.getResourceConfig(language);
      if (resourceConfig) {
        const result = await this.resourceParser.parseResource(resourceConfig);
        if (result) {
          this.languagePackages.set(language, {
            language,
            data: result.translations
          });
          logger.info('从本地资源加载语言包成功', { language });
          return true;
        }
      }

      logger.warn('语言包加载失败', { language });
      return false;
    } catch (error) {
      logger.error('加载语言包出错', { 
        language, 
        error: error instanceof Error ? error.message : String(error) 
      });
      return false;
    }
  }

  /**
   * 获取支持的语言列表
   */
  public async getLanguages(): Promise<Array<{ language: string; name: string; path: string }>> {
    if (this.networkManager) {
      return this.networkManager.getLanguages();
    }
    return [];
  }

  /**
   * 获取资源配置
   */
  private getResourceConfig(language: string): ResourceConfig | null {
    // TODO: 从TranslationConfig中获取资源配置
    return null;
  }
} 